<template>
  <el-input
    v-model="value"
    :id="'w' + props.formCtrlId"
    :name="'w' + props.formCtrlId"
    :type="props.controlType"
    :size="props.size"
    :validate-event="props.validateEvent"
    :show-word-limit="props.showWordLimit"
    :clearable="props.clearable"
    :resize="props.resize"
    :disabled="props.disabled"
    @clear="mySubmit"
    readonly
  >
    <template #prepend>
      <el-autocomplete
        v-model="selectValue"
        :fetch-suggestions="fetchSuggestions"
        :label="props.selectProp"
        :value-key="props.selectProp"
        @blur="setInputValue"
        @click="getRecord"
        @change="initMethod"
      ></el-autocomplete>
    </template>
  </el-input>
</template>

<script lang="ts" setup>
import { defineProps, ref } from "vue";
import api from "@/utils";
import { AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import FormItemCtrl from "@/components/form/formItem/FormItemCtrl";
import { BaseFormItem } from "@/components/form/formItem/FormItemMeta";

const selectValue = ref();

export interface SelectAutoInputProps extends BaseFormItem {
  modelValue: string | null;
  formCtrlId?: number; // 控件id, 区分组件
  colName?: string; // 字段名称
  isClear?: boolean; // 连续添加是否需要清空该字段
  controlType?: string; // 控件类型
  size?: string; // 尺寸 medium / small / mini
  optionList?: Array<unknown>; // 备用选项
  validateEvent?: boolean; // 输入时是否触发表单的校验
  showWordLimit?: boolean; // 是否显示输入字数统计
  clearable?: boolean; // 是否显示清空标记
  resize?: string; // 是否能被用户缩放 none, both, horizontal, vertical
  disabled?: boolean;
  searchUrl?: string;
  inputProp?: string;
  selectProp?: string;
}

const props = withDefaults(defineProps<SelectAutoInputProps>(), {
  modelValue: "",
  formCtrlId: 10001,
  colName: "no",
  isClear: true,
  size: "default",
  controlType: "text",
  optionList: () => [],
  validateEvent: true,
  showWordLimit: true,
  clearable: true,
  resize: "none",
  disabled: false,
  searchUrl: "",
  inputProp: "userNo",
  selectProp: "username",
});

const dataList = ref([] as Record<string, any>[]);
const setDataList = (data: Record<string, unknown>[] | null) => {
  dataList.value = data as Record<string, unknown>[];
};

const getRecord = async () => {
  setTimeout(() => {
    api.http
      .postJson(props.searchUrl, {})
      .then((res: AxiosResponse) => {
        setDataList(res.data.data);
      })
      .catch(() => {
        ElMessage.error("获取数据失败!");
      });
  }, 50);
};

const initMethod = () => {
  setTimeout(() => {
    if (value.value !== undefined) {
      if (value.value !== null) {
        getRecord()
          .then(() => {
            setSelectValue();
          })
          .catch();
      }
    }
  }, 300);
};

initMethod();

const fetchSuggestions = (
  queryString: string,
  callback: (data: Array<Record<string, unknown>>) => void
) => {
  setTimeout(() => {
    const results = queryString
      ? dataList.value.filter((item) => {
          return (
            item[props.selectProp]
              .toLocaleLowerCase()
              .indexOf(queryString.toLocaleLowerCase()) === 0
          );
        })
      : dataList.value;
    console.log(dataList.value);
    callback(results);
  }, 300);
};

const setInputValue = () => {
  setTimeout(() => {
    const filterList = dataList.value.filter((item) => {
      return (
        item[props.selectProp]
          .toLocaleLowerCase()
          .localeCompare(selectValue.value) === 0
      );
    });
    if (filterList.length === 1) {
      value.value = filterList[0][props.inputProp];
    } else {
      value.value = null;
    }
    console.log(selectValue.value);
  }, 200);
};

const setSelectValue = () => {
  setTimeout(() => {
    console.log(dataList.value);
    const filterList = dataList.value.filter((item) => {
      return (
        item[props.inputProp].toLocaleLowerCase().localeCompare(value.value) ===
        0
      );
    });
    if (filterList.length !== 1) {
      selectValue.value = null;
    } else {
      selectValue.value = filterList[0][props.selectProp];
    }
  }, 300);
};

const emit = defineEmits(["update:modelValue", "myChange", "input", "change"]);

const { value, mySubmit } = FormItemCtrl(props, emit);
</script>

<style>
.el-input-group__prepend {
  background: #ffffff;
  padding: 0;
}
</style>
<style scoped></style>
